package com.zmz.Stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/16:21
 * @Description: 规约，也称缩减，是把一个流缩减成一个值，能实现对集合求求和，求乘积和求最值操作。
 */
public class Stream07 {
    public static void main(String[] args) {
        //1.求Integer集合的元素之和,乘积和最大值
        List<Integer> list = Arrays.asList(1, 2, 2, 4, 2, 1);
        //以前求和
        int sum = 0;
        for (Integer integer : list) {
            sum += integer;
        }
        System.out.println(sum);
        //使用reduce求和    Optional<T> reduce(BinaryOperator<T> accumulator); 第一个得加get()因为返回值类型是 Optional<java.lang.Integer>
        Integer sum1 = list.stream().reduce(Integer::sum).get();
        Integer sum2 = list.stream().reduce(0, Integer::sum);
        Integer sum3 = list.stream().reduce((x, y) -> x + y).get();
        System.out.println(sum1);
        System.out.println(sum2);
        System.out.println(sum3);
        System.out.println("--------");
        //求乘积
        Integer cj = list.stream().reduce((x, y) -> x * y).get();
        Integer cj2 = list.stream().reduce(1, (x, y) -> x * y);
        System.out.println(cj2);

        //求最大值1
        Integer max1 = list.stream().max(Integer::compareTo).get();
        System.out.println(max1);
        //求最大值2
        Integer max2 = list.stream().reduce(Integer::max).get();
        System.out.println(max2);
        //求最大值3
        Integer max3 = list.stream().reduce((x, y) -> x > y ? x : y).get();
        System.out.println(max3);
        //求员工工资之和和最高工资
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        //方法一  先找出所有得工资再求和
        Integer sumSalary = personList.stream().map(t -> t.getSalary()).reduce(Integer::sum).get();
        System.out.println(sumSalary);

        //方法二
        Integer sumSalary2 = personList.stream().map(t -> t.getSalary()).reduce(0, (x, y) -> x + y);
        System.out.println(sumSalary2);
        //方法三
        Integer sumSalary3 = personList.stream().map(t -> t.getSalary()).reduce((x, y) -> x + y).get();
        System.out.println(sumSalary3);

        //求最高工资方法一  s用来存放结果用结果与较高工资比较 返回结果
        Integer maxSalary = personList.stream().reduce(0, (s, p) -> s > p.getSalary() ? s : p.getSalary(), Integer::sum);
        System.out.println(maxSalary);
        //
    }
}
